using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;


namespace RandomRat {

	/// <summary>
	/// A TextBox which only accepts numerical input.
	/// </summary>
	public class NumberBox : System.Windows.Forms.TextBox {

		public NumberBox() : base() {}

		protected override void OnKeyPress(KeyPressEventArgs e) {
			// If its a digit charecter or a control char (like backspace or del), continue prossesing
			if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || 
				Control.ModifierKeys == Keys.Alt ||	Control.ModifierKeys == Keys.Control) {	
				base.OnKeyPress(e);
			} else {
				e.Handled = true;
			}
		}

		protected override void WndProc(ref Message m) {
			// Make sure no non numbers sneek in via a Past comand
			if (m.Msg == 770) { // 0x302 past
				// If the clipboard has text data which is not entierly
				// composed of numbers, kill the msg.
				IDataObject data = Clipboard.GetDataObject();
				if(data.GetDataPresent(DataFormats.Text)) {
					string text = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

					// If the clipboard holds a number, pass the msg on
					if (stringIsNumber(text)) {
						base.WndProc(ref m);
					}
				}
			} else {
				// msg is not a past, pass it on
				base.WndProc(ref m);
			}
			
		}

		public override string Text {
			// If text is assined that is not a number, ignore it
			set { if (stringIsNumber(value)) base.Text = value;	}
			get { return base.Text; }
		}

		/// <summary>
		/// Returns wheather text param is a number
		/// </summary>
		private bool stringIsNumber(string text) {
			char[] charArray = text.ToCharArray();
			for (int i = 0; i < charArray.Length; i++) {
				if (!char.IsDigit(charArray[i])) {
					return false;
				}
			}
			return true;
		}

		override protected void OnValidating(CancelEventArgs e) {
			ValidateAsInt();
		}

		public void ValidateAsInt() {
			if (this.Text.Length > 1 && this.Text[0] == '0') {
				char[] text = this.Text.ToCharArray();
				
				int numOfLeadingZeros = 0;

				foreach (char c in text) {
					if (c == '0') {
						numOfLeadingZeros++;
					} else {
						break;
					}
				}

				int curSelectionStart = this.SelectionStart;
			
				if (numOfLeadingZeros != text.Length) {
					StringBuilder sb = new StringBuilder(text.Length - numOfLeadingZeros);

					for (int i = numOfLeadingZeros; i < text.Length; i++) {
						sb.Append(text[i]);
						//sb.Append('4');
					}
					this.Text = sb.ToString();
					this.SelectionStart = curSelectionStart;
				
				} else {
					this.Text = "0";
					this.SelectionStart = 1;
				}				
			}           			
		}
		
	}
}